import router from './index'
import Layout from '../views/Layout.vue'
import { useMenuStore } from '../stores/menu'

export async function ensureDynamicRoutes() {
  let menuStore, tree, children
  try {
    menuStore = useMenuStore()
    tree = (await menuStore.load()) || []
    children = menuStore.buildRoutes(tree)
    
    // 获取现有的根路由
    const rootRoute = router.getRoutes().find(route => route.path === '/')
    if (rootRoute && children && Array.isArray(children) && children.length > 0) {
      // 如果根路由存在，添加动态子路由
      children.forEach(r => {
        // 确保路由对象存在且有path属性
        if (r && typeof r === 'object' && r.path && typeof r.path === 'string' && !router.hasRoute(r.path)) {
          // 确保动态路由有正确的面包屑信息
          const routeWithMeta = {
            ...r,
            meta: {
              ...r.meta,
              title: r.meta?.title || `breadcrumb.${r.path.replace('/', '')}`,
              icon: r.meta?.icon || 'Menu'
            }
          }
          router.addRoute(rootRoute.name, routeWithMeta)
        }
      })
    }
  } catch (error) {
    console.error('Failed to ensure dynamic routes:', error)
    // 记录更详细的错误信息以便调试
    console.error('Error details:', {
      message: error.message,
      stack: error.stack,
      menuStore: !!menuStore,
      tree: tree,
      children: children
    })
  }
}


